/*
 * @Author: your name
 * @Date: 2020-07-06 16:34:05
 * @LastEditTime: 2020-07-22 15:24:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \thinkjs-test\src\service\UniPushResetService.js
 */

import {
    axios
} from '../utils/request';
module.exports =class extends think.Service {
    constructor(options) {
        this.GTConfig = options;//think.config("geTuiConfig");
        this.tokenInfo = {};
        this.GTdata = {
            "requestid": Date.now() + "abcdefg", //注意requestid不能为纯数字
            "title": Date.now() + "测试title",
            "text": Date.now() + "测试text",
            "content": Date.now() + "测试content",
            alias: 'testDemo'
        }
        this.cid = 'bb9e0c013d18d9c3b459bdf8b1aa34b5';
        this.cid2 = '390179eae678a4ea3b7dbcdda28b8529';
    }



    async getToken() {
        if (this.tokenInfo.token && this.tokenInfo.expire_time > +new Date()) {
            return this.tokenInfo.token;
        }
        const {
            APPID,
            APPKEY,
            MASTERSECRET
        } = this.GTConfig;

        var timestamp = Date.now();

        let sign = await require('crypto').createHash('sha256').update(APPKEY + timestamp + MASTERSECRET).digest('hex'); //hex是十六进制
        let res = await axios({
            url: `http://restapi.getui.com/v2/${APPID}/auth`,
            method: 'post',
            contentType: 'json',
            data: {
                sign,
                timestamp,
                appkey: APPKEY
            },
            responseType: 'json'
        })
        this.tokenInfo = res.data;
        return res.data.token;
    }

    /**
     *单推
     *
     * @param {*} data
     * @returns
     */
    async pushMessageToSingle(data) {
        const clientID = data && data.cid || this.cid2 || 'bb9e0c013d18d9c3b459bdf8b1aa34b5';
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;

        const requestConfig =await this.createMessage({
            clientID,
            title,
            content,
        });
        let res = await axios(requestConfig)
        return res.data;
    }

    // /push/single/batch/cid
    /**
     *批量-单推
     *
     * @param {*} data
     * @returns
     */
    async pushManyMessageToSingle(data) {
        console.log('data:',data);
        const appId = this.GTConfig.APPID;
        const cidList = data && data.cidList || [this.cid2];
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        const is_async = data && data.is_async || false; //是否异步推送，异步推送不会返回data
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/push/single/batch/cid`;
        let msg_list = [];
        for (let index = 0; index < cidList.length; index++) {
            const element = cidList[index];
            requestConfig.data.audience.cid = [element];
            msg_list.push(requestConfig.data)
        }
        requestConfig.data = {
            is_async: is_async,
            msg_list: msg_list
        }
        return await axios(requestConfig);
    }


    /**
     *执行别名批量推
     *
     * @param {*} data
     * @returns
     */
    async pushAliasToApp(data){
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        let alias = data && data.alias || [this.GTdata.alias]; //是否异步推送，异步推送不会返回data
        if(alias && typeof alias =='string' && alias.indexOf(',')>=0){
            alias = alias.split(',');
        }else if(alias && typeof alias =='string'&& alias.indexOf(',')==-1){
            alias= [alias];
        }
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        const taskId = await this.getTaskIdByMessage(data);
        console.log('taskId:',taskId);
        if(!taskId){
            return 'taskId is null';
        }
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/push/list/alias`;
        
        requestConfig.data = {
            "audience": {
                "alias": alias
            },
            "taskid": taskId,
            "is_async": false
        }
        let ret;
        try{
            ret= await axios(requestConfig);
        }catch(e){
            ret = e.data;
        }
        return ret;
    }

    /**
     *获取taskid 
     *
     * @param {*} data
     */
    async getTaskIdByMessage(data){
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/push/list/message`;
        let ret;
        try{
            ret= await axios(requestConfig);
        }catch(e){
            ret = e.data;
        }
        return ret&&ret.data && ret.data.taskid;
    }

    /**
     *消息基本结构体
     *
     * @param {*} options
     * @returns
     */
    async createMessage(options) {
        const token = await this.getToken();
        const {appId} = this.GTConfig;
        const requestid = options&& options.requestid ||this.GTdata.requestid;
        const {
            clientID,
            title,
            content,
        } = options;

        const payload = `{"title":${title},"content":"${content}","sound":"default","payload":${requestid}}`; //
        
        return {
            url: `http://restapi.getui.com/v2/${appId}/push/single/cid`,
            method: 'post',
            headers: {
                "Content-Type": "application/json;charset=utf-8",
                "token": token
            },
            contentType: 'json',
            responseType: "json",
            data: {
                "request_id": requestid,
                "audience": {
                    cid: [clientID]
                },
                "settings": {
                    "ttl": 3600000,
                    "strategy": {
                        "default": 1,
                        "ios": 4,
                        "st": 4
                    }
                },
                "push_message": {
                    "network_type": 0,
                    "notification": {
                        "title": title,
                        "body": content,
                        "click_type": "startapp",
                        // intent:intent
                    }
                },
                "push_channel": {
                    "android": {
                        "ups": {
                            "notification": {
                                "title": title, // "请填写android标题",
                                "body": content, //"请填写android内容",
                                "click_type": "startapp",
                                // "url":"https://www.baidu.com/"
                                // intent:intent
                            }
                        }
                    },
                    "ios": {
                        "type": "notify",
                        "payload": payload,
                        "aps": {
                            "alert": {
                                "title": title, // "请填写ios标题",
                                "body": content, //"请填写ios内容",
                            },
                            "content-available": 0
                        },
                        // "auto_badge": "+1"
                    }
                }
            },
        };
    }
    /**
     *单推 alias
     *
     * @param {*} data
     * @returns
     */
    async pushMessageToSingleByAlias(data) {
        const appId = this.GTConfig.APPID;
        const alias = data && data.alias || this.GTdata.alias;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        const audience = {
            "alias": [alias]
        }

        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/push/single/alias`;
        requestConfig.data.audience = audience;
        console.log('requestConfig:', requestConfig);
        let ret = await axios(requestConfig);

        return ret;
    }


    /**
     *群推
     //带有tag的，对tag用户进行推送，没有则全部推送
     *
     * @param {*} data
     */
    async pushMessageToApp(data) {
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        const group_name = data && data.group_name || ''; //"请填写任务组名";
        const tag = data && data.tag || '';
        let audience = "all";
        if (tag) {
            audience = {
                fast_custom_tag: tag
            }
        }
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/push/all`;
        requestConfig.data.audience = audience;
        requestConfig.data.group_name = group_name;
        let ret;
        try{
            ret =await axios(requestConfig);
        }catch(e){
            ret = e.data;
        }
        return ret;

    }

    


    /**post 绑定别名 一个cid只能绑定一个别名，若已绑定过别名的cid再次绑定新别名，则前一个别名会自动解绑，并绑定新别名。
     *delete 批量解除别名与cid的关系
     *
     * @param {*} data
     */
    async bindAlias(data) {
        const alias = data && data.alias || this.GTdata.alias;
        const isAdd = data && data.is_add||true;
        const appId = this.GTConfig.APPID;
        const cidList = data && data.cidList || [this.cid2];
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
        let data_list = [];

        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/alias`;
        for (let index = 0; index < cidList.length; index++) {
            const element = cidList[index];
            data_list.push({
                "cid":element,
                "alias":alias
            })
        }
        console.log('data_list:',data_list);
        requestConfig.data = {
            data_list: data_list
        }
        if(!isAdd){
            requestConfig.method = 'delete';
        }
        return await axios(requestConfig);
    }
    /**
     *根据cid查询alias
     *
     * @param {*} data
     * @returns
     */
    async queryAlias(data) {
        const cid = data && data.cid || this.cid2;
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/alias/cid/${cid}`;
        requestConfig.data = null;
        requestConfig.method = 'get';
        let res;
        try{
            res= await axios(requestConfig);
        }catch(e){
            console.log('error:',e);
            res = e.data;
        }
        return res;
    }

    /**
     *批量解绑别名
     *
     * @param {*} data
     */
    async unBindAlias(data) {
        const alias = data && data.alias || this.GTdata.alias;
        const cidList = data && data.cidList||[this.cid];
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
        let data_list=[];
        for (let index = 0; index < cidList.length; index++) {
           const element = cidList[index];
           data_list.push({
            "cid":element,
            "alias":alias
           })
        }
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/alias`;
        requestConfig.method = 'delete';
        requestConfig.data={
            data_list:data_list
        };
        return await axios(requestConfig);
    }

/**
     *解绑所有与该别名绑定的cid
     *
     * @param {*} data
     */
    async removeAlias(data) {
        const alias = data && data.alias || this.GTdata.alias;
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/alias/${alias}`;
        requestConfig.method = 'delete';
        requestConfig.data=null;
        return await axios(requestConfig);
    }

/**
     *一个用户绑定一批标签
     此接口有频次控制，tag的长度、个数、总长度也有限制，申请修改请联系邮箱：lieg@getui.com 。
     *
     * @param {*} data
     */
    async bindCustomTagListByCid(data) {
        const cid = data && data.cid ||this.cid;
        let custom_tag = data && data.custom_tag || [this.GTdata.custom_tag];
        if(custom_tag&& typeof custom_tag =="string" &&custom_tag.indexOf(',')>=0){
            custom_tag = custom_tag.split(',');
        }
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
       
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/custom_tag/cid/${cid}`;
        requestConfig.data={
            "custom_tag": custom_tag
        };
        return await axios(requestConfig);
    }
    
    
    /**
     *一批用户绑定一个标签
     此功能需要申请开通才可以使用，tag的长度也有限制，申请修改请联系邮箱：lieg@getui.com
     *
     * @param {*} data
     */
    async bindCustomTagByCidList(data) {
        const is_unbind = data&&data.is_unbind||false;//如果为解绑
        let cidList = data && data.cidList ||[this.cid];
        if(cidList&& typeof cidList =="string" &&cidList.indexOf(',')>=0){
            cidList = cidList.split(',');
        }
        const custom_tag = data && data.custom_tag || [this.GTdata.custom_tag];
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
       
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/custom_tag/batch/${custom_tag}`;
        if(!is_unbind){
            requestConfig.method = 'put';
        }else{
            requestConfig.method = 'delete';
        }
        requestConfig.data={
            "cid": cidList
        };
        let ret;
        try{
            ret =await axios(requestConfig);
        }catch(e){
            console.log('error:',e);
            ret = e.data;
        }
        return ret
    }
    

    /**
     *解绑标签
     * 此功能需要申请开通才可以使用，tag的长度也有限制，申请修改请联系邮箱：lieg@getui.com
     * @param {*} data
     */
    async CustomTagByCidList(data) {
        let cidList = data && data.cidList ||[this.cid];
        if(cidList&& typeof cidList =="string" &&cidList.indexOf(',')>=0){
            cidList = cidList.split(',');
        }
        const custom_tag = data && data.custom_tag || [this.GTdata.custom_tag];
        const appId = this.GTConfig.APPID;
        const title = data && data.title || this.GTdata.title;
        const content = data && data.content || this.GTdata.content;
        
       
        const requestConfig = await this.createMessage({
            title,
            content,
        });
        requestConfig.url = `http://restapi.getui.com/v2/${appId}/user/custom_tag/batch/${custom_tag}`;
        requestConfig.method = 'delete';
        requestConfig.data={
            "cid": cidList
        };
        
        return await axios(requestConfig);
    }
}